<template>
    <!-- <div class="thought-clps" v-if="showThoughtClps"> -->
    <div :class="isOpen ? 'thought-clps' : 'thought-clps thought-clps-open'" v-if="showThoughtClps"
         :style="{ 'max-width':(webIMSource === 'client' && isMobile)  ? '352px' : '680px' }" >
        <v-popper ref="littleTagPop" clazz="pop-demo" :use-arrow="true">
            <div class="pop-demo-list" v-for="pop in popperList" :key="pop.id">
                <!-- <a :href="pop.url" target="_blank">{{pop.id + '.' + pop.name }} ></a> -->
                <v-button type="link" kind="primary" @click="openSearchUrl(pop, pop.id)">
                    <!-- {{pop.id + '.' + pop.name }} -->
                    {{ pop.id }}.{{ isMobile ? formattedEllipsis(pop.title, 15) : formattedEllipsis(pop.title) }}
                    <v-icon remote name="arrow_right_line" size="12" valign="-1"></v-icon>
                </v-button>
            </div>
        </v-popper>
        <div class="thought-clps-title" @click="toggleCollapse">
            <img  v-if="agentThought.is_workflow" class="logo-split" src="@/assets/img/thought-workflow.svg" alt="split" />
            <span v-if="agentThought.is_workflow" >{{`{ ${agentThought.workflow_name} }工作流`}}</span>
            <span class="thought-clps-title-desc">{{!isOpen ? '展开思考过程' : '收起思考过程'}}</span>
            <v-icon :remote="true" name="arrow_down_small_line" size="12" class="tokens-bd__header__icon"
                    :rotate="isOpen ? 180 : 0"></v-icon>
        </div>
        <div class="thought-clps-content" v-show="isOpen">
            <div v-for="item in agentThought.procedures" :key="item.index">
                <div class="thought-title" @click="openRunNodes(item)">
                    <div class="thought-title-container">
                        <img class="thought-title-icon" :src="item.icon" />
                        <span class="thought-title-name">{{ item.title }}</span>
                        <!-- <v-spinner v-if="ele.status === TOKENS_STATUS.pending" status="default"></v-spinner> -->
                        <v-icon v-if="item.status === TOKENS_STATUS.error" name="basic_warning_line"
                                style="color:#FF8345;" remote size="16" />
                        <v-icon v-else name="basic_finish_line" style="color: #0FB87F" remote size="16" />
                    </div>
                    <div class="thought-title-container thought-title-elapsed">
                        <span>{{ item.elapsed ? item.elapsed / 1000 : 0 }}s</span>
                        <v-icon :remote="true" name="arrow_down_small_line" size="12" class="thought__header__icon"
                                :rotate="isOpenDtl[item.index] ? 180 : 0"></v-icon>
                    </div>
                </div>
                <div class="thought-detail" v-if="isOpenDtl[item.index]">
                    <!-- 区分展示思考过程内容
                    1.name === thought 按照md展示
                    2.除了name === thought 以外 display_type === 1 && status === success 用参考来源
                    3.除了name === thought 以外 status === success 用json
                    其他使用md -->
                    <div v-if="item.show_type === 'md'">
                        <!-- <VueMarkdown table-class="table" class="answer-md"
                                     :style="{ 'max-width': webIMSource === 'client' && isMobile ? '310px' : '680px' }"
                                     :source="fixMarkdownOrderedList(replaceLinks(item.debugging.content))"
                                     :anchorAttributes="{ target: '_blank' }" :linkify="false" /> -->
                        <MsgContent :showTags="false" :recordId = "item.name + item.index" :isReplaceLinks="true" :loadingMessage="false" :content="item.debugging.content" :isMdExpand="true" :clazzMd="`question-text ${webIMSource === 'client' && isMobile ? 'question-text-mobile' : ''}`" :styleObj="{ 'max-width': webIMSource === 'client' && isMobile ? '352px' : '680px' }" />
                    <!-- <MsgContent @imageClick="imageClick" @littleTagClick="littleTagClick" :showTags="true" :recordId = "item.record_id" :isReplaceLinks="true" :loadingMessage="item.loading_message" :content="item.content" :isFinal="item.is_final" :isMdExpand="true" :clazzMd="`question-text ${webIMSource === 'client' && isMobile ? 'question-text-mobile' : ''}`" :styleObj="{ 'max-width': webIMSource === 'client' && isMobile ? '352px' : '680px' }" /> -->
                    </div>
                    <div v-if="item.show_type === 'search-reference' || item.show_type === 'knowledge-reference'">
                        <!-- <MsgContent :showTags="false" :recordId = "item.name + item.index" :isReplaceLinks="true" :loadingMessage="false" :content="item.debugging.content" :isMdExpand="true" :clazzMd="`question-text ${webIMSource === 'client' && isMobile ? 'question-text-mobile' : ''}`" :styleObj="{ 'max-width': webIMSource === 'client' && isMobile ? '352px' : '680px' }" /> -->
                        <MsgContent @littleTagClick="littleTagClick" :showTags="true" :recordId = "item.name + '@@' + item.index" :isReplaceLinks="true" :loadingMessage="false" :content="item.display_content" :isFinal="true" :isMdExpand="true" :clazzMd="`question-text ${webIMSource === 'client' && isMobile ? 'question-text-mobile' : ''}`" :styleObj="{ 'max-width': webIMSource === 'client' && isMobile ? '352px' : '680px' }" />
                        <Reference :references-list="item.debugging.references"/>
                    </div>
                    <div v-if="item.show_type === 'json'">
                        <vue-json-pretty v-if="!isEmpty(item.debugging.content) && isJSON(item.debugging.content)" showIcon="true"
                                         :data="JSON.parse(item.debugging.content)"></vue-json-pretty>
                        <div v-else>
                            <!-- 兜底处理不是json的状况 -->
                            <MsgContent :showTags="false" :recordId = "item.name + item.index" :isReplaceLinks="true" :loadingMessage="false" :content="item.debugging.content" :isMdExpand="true" :clazzMd="`question-text ${webIMSource === 'client' && isMobile ? 'question-text-mobile' : ''}`" :styleObj="{ 'max-width': webIMSource === 'client' && isMobile ? '352px' : '680px' }" />
                        </div>
                    </div>

                </div>
                <!-- 展示转接部分 switch 取值为 workflow或者main -->
                <!-- 1. main Agent->workflow
                    [Agent转交对话] {同程开发票}工作流 接管当前对话
                    2. workflow->main Agent
                    [{同程开发票}工作流转交对话] Agent 接管当前对话 -->
                <div class="thought-tips" v-if="item.switch === 'workflow'">
                    <div class="thought-tips-workflow">
                        [Agent转交对话] {{`{ ${item.workflow_name} }`}} 工作流接管当前对话
                    </div>
                </div>
                <div class="thought-tips" v-if="item.switch === 'main'">
                    <div class="thought-tips-workflow">
                        [{{`{ ${item.workflow_name} }`}}工作流转交对话] Agent 接管当前对话
                    </div>
                </div>
            </div>
        </div>
        <!-- title -->
        <!-- <div :class="isOpen ? 'thought-clps-title' : 'thought-clps-title-isOpen'" @click="toggleCollapse" >
            <img class="logo-split" src="@/assets/img/thought.svg" alt="split" />
            <span class="thought-clps-title-desc">展开思考过程</span>
            <span v-if="agentThought.is_workflow" >[Agent转交对话] {{agentThought.workflow_name}}工作流接管当前对话</span>
            <v-icon :remote="true" name="arrow_down_small_line" size="12" class="thought__header__icon"
                    :rotate="isOpen ? 180 : 0"></v-icon>
        </div> -->
    </div>
</template>

<script>
import VueMarkdown from 'vue-markdown';
import { TOKENS_STATUS } from '@/constants';
import { replaceLinks, formattedEllipsis } from '@/utils';
import Reference from './reference-component.vue';
import { isJSON, convertToCapitalizedCamelCase, isEmpty } from '@/utils/util';
import VueJsonPretty from 'vue-json-pretty';
import 'vue-json-pretty/lib/styles.css';
export default {
    components: {
        VueMarkdown,
        Reference,
        VueJsonPretty
    },
    data () {
        return {
            isOpen: true,
            isMobile: false,
            TOKENS_STATUS,
            popperList: [],
            oldPopDemo: null,
            isOpenDtl: []
        };
    },
    props: {
        agentThought: {
            type: Object,
            default: null
        }
        // isOpen: {
        //     type: Boolean,
        //     default: true
        // }
    },
    computed: {
        showThoughtClps () {
            return this.agentThought && this.agentThought.procedures && this.agentThought.procedures.length > 0;
        }
        // collapseHeaderClass () {
        //     // thought-clps__header
        //     return {
        //         'thought-clps__header': true,
        //         'headerOpen': this.isOpen,
        //         'headerClose': !this.isOpen
        //     };
        // }

    },
    methods: {
        replaceLinks,
        isEmpty,
        formattedEllipsis,
        isJSON,
        convertToCapitalizedCamelCase,
        collapseOperate (bool) {
            this.isOpen = bool;
        },
        littleTagClick (e, r) {
            let name = r.split('@@')[0];
            // let id = r.split('@@')[1];

            const findMsg = this.agentThought.procedures.find(el => el.name === name);
            console.error('【content】littleTagClick  2222221=======》', e, e.outerText, r, name, findMsg);

            let outerTextArr = e.outerText.split('');
            this.popperList = findMsg.debugging.references.filter(ell => outerTextArr.includes(ell.id.toString()));

            if (this.oldPopDemo) {
                this.$refs['littleTagPop'].unbindTrigger(this.oldPopDemo);
            }
            if (e) {
                this.$refs['littleTagPop'] && this.$refs['littleTagPop'].bindTrigger(e, 'manual');
                this.$refs['littleTagPop'] && this.$refs['littleTagPop'].update();
                this.$refs['littleTagPop'] && this.$refs['littleTagPop'].show();
                this.oldPopDemo = e;
            }
        },
        openSearchUrl (refer, index) {
            console.error('【reference】', refer, index);
            window.open(refer.url);
        },
        handleOutsideClick (event) {
            if (!this.oldPopDemo) { return; };
            const firstElement = document.getElementsByClassName('pop-demo')[0];
            console.log('【clickoutside】===========>', event.target, this.oldPopDemo, firstElement);
            if (this.oldPopDemo.contains(event.target) || firstElement.contains(event.target)) {
            } else {
                if (this.oldPopDemo) {
                    this.$refs['littleTagPop'] && this.$refs['littleTagPop'].unbindTrigger(this.oldPopDemo);
                }
                // 调用你想要执行的方法
                this.$refs['littleTagPop'] && this.$refs['littleTagPop'].hide();
                this.oldPopDemo = null;
            }
        },
        // getShowType (item) {
        //     // 展示种类 md json lke
        //     if (item.name === 'thought') {
        //         return 'md';
        //     } else if (item.status === 'success') {
        //         // 在clientData处还有特殊处理
        //         if (item.debugging && item.debugging.display_type === 1) {
        //             return 'lke-reference';
        //         } else {
        //             return 'json';
        //         }
        //     } else {
        //         return 'json';
        //     }
        // },
        openRunNodes (m) {
            // if (m.node_type === 4) return;
            // console.log('000000token   openRunNodes', m, this.isOpenDtl, this.isOpenDtl[m.NodeId])
            this.isOpenDtl[m.index] = !this.isOpenDtl[m.index];
            this.isOpenDtl = Object.assign({}, this.isOpenDtl);
            // console.log('000000token   openRunNodes111111', m, this.isOpenDtl, this.isOpenDtl[m.NodeId])
        },
        fixMarkdownOrderedList (mdText) {
            // 如果文本为空，则直接返回
            if (!mdText) return mdText;
            // 分割文本为行
            const lines = mdText.split('\n');

            // 遍历每一行
            for (let i = 0; i < lines.length; i++) {
                // 检查当前行是否是有序列表项
                if (/^\d+\.\s/.test(lines[i])) {
                    // 检查下一行是否是错误的有序列表项
                    if (lines[i + 1] && /^\d+\.\S/.test(lines[i + 1])) {
                        // 在序号和点之间添加空格
                        lines[i + 1] = lines[i + 1].replace(/(\d+)\.(\S)/, '$1. $2');
                    }
                }
            }

            // 合并行为新的文本
            const fixedMdText = lines.join('\n');

            return this.xssHandlerProcess(fixedMdText);
        },
        toggleCollapse () {
            console.log(23333, this.isOpen);
            this.isOpen = !this.isOpen;
            // this.$emit('update:isOpen', !this.isOpen);
        }
    },
    watch: {
        agentThought: {
            handler (val, oldValue) {
                // console.log('【agentThought】', val);
                if (val && val.procedures && val.procedures.length > 0) {
                    val.procedures.forEach(el => {
                        // 给每一个，增加一个展开收起的标识
                        if (!this.isOpenDtl.hasOwnProperty(el.index)) {
                            this.isOpenDtl[el.index] = true;
                        } else {
                            if (this.isOpenDtl[el.index] === undefined) {
                                this.isOpenDtl[el.index] = true;
                            }
                        }
                    });
                }

                if (val && val.status_summary === TOKENS_STATUS.pending) {
                    this.isCollapsed = true;
                } else {
                    this.isCollapsed = false;
                }
                console.log('000000000000tokens222', val, this.isOpenDtl);
            },
            immediate: true // 立即触发handler函数
        }
    },
    created () {
        // console.error('【agentThought】1', this.agentThought);
    },
    mounted () {
        // console.error('【agentThought】12', this.agentThought);
        document.addEventListener('click', this.handleOutsideClick);
        const sDom = document.querySelector('.client-chat');
        sDom.addEventListener('scroll', () => {
            this.$refs['littleTagPop'] && this.$refs['littleTagPop'].hide();
        });
    },
    beforeDestroy () {
        // 移除全局事件监听器
        document.removeEventListener('click', this.handleOutsideClick);
    }
};
</script>

<style lang="less" scoped>
div {
  margin: 0;
  padding: 0;
  border: 0;
  box-sizing: border-box;
}

.isShow {
  // border-radius: var(--radius-large);
}
.thought__header__icon {
}

// .thought-tips-workflow{
// }

.thought-clps.thought-clps-open {
  // border: none;
  // background: transparent;
  // color: var(--color-text-caption);
  .thought-clps-title {
    padding: 12px 0 0 0;
  }
}

.thought-clps {
  // background-color: #fff;
  // border-radius: var(--radius-large);
  // background: var(--color-bg-1);
  // border: 1px solid var(--border---color-border-normal, rgba(4, 34, 75, 0.13));

  &-title {
    // background-color: #fff;
    color: var(--color-text-caption);
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: 16px;
    /* 133.333% */
    cursor: pointer;
    padding: 12px 0;

    display: flex;
    // padding: 12px 16px 0 16px;
    // height: 43px;
    // padding: 6px 24px;
    align-items: center;
    gap: var(--spacing-tight);

    // border-radius: var(--radius-0) var(--radius-0) var(--radius-large) var(--radius-large);
    // background: var(--color-gray-0);
    &-desc:hover {
      background: linear-gradient(
        90deg,
        #62c3ff -7.64%,
        #5b89ff 49.61%,
        #7978ff 100%
      );
      // background: linear-gradient(90deg, color(display-p3 0.4824 0.7569 1) -7.64%, color(display-p3 0.3961 0.5333 1) 49.61%, color(display-p3 0.4745 0.4706 1) 100%);
      background-clip: text;
      color: transparent;
    }
  }
  .thought-clps-title-isOpen {
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: 16px;
    /* 133.333% */
    cursor: pointer;
    padding: 6px;
    display: flex;
    align-items: center;
    gap: var(--spacing-tight);
    width: fit-content;
    border-radius: var(--radius-large);
    border: var(--border-thickness) solid var(--color-border-normal);
    background: var(--color-bg-1);
  }

  // &-title:hover {
  //     background: linear-gradient(90deg, #62C3FF -7.64%, #5B89FF 49.61%, #7978FF 100%);
  //     // background: linear-gradient(90deg, color(display-p3 0.4824 0.7569 1) -7.64%, color(display-p3 0.3961 0.5333 1) 49.61%, color(display-p3 0.4745 0.4706 1) 100%);
  //     background-clip: text;
  //     color: transparent;
  // }

  &-content {
    display: flex;
    padding: var(--spacing-base-loose);
    // padding: var(--spacing-base-loose) 24px;
    flex-direction: column;
    // align-items: flex-start;
    gap: 12px;
    align-self: stretch;
    // margin-top: 12px;
    border-radius: var(--radius-large);
    background: var(--color-bg-0);

    .thought-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;

      .thought-title-container {
        display: flex;
        align-items: center;
        gap: 5px;
      }

      .thought-title-icon {
        display: flex;
        width: 16px;
        height: 16px;
        flex-direction: column;
        justify-content: center;
        border-radius: 8px;
      }

      .thought-title-name {
        color: var(--color-text-primary);
        font-size: 12px;
        font-style: normal;
        font-weight: 600;
        line-height: normal;
      }

      .thought-title-elapsed {
        color: var(--color-text-caption);
        font-family: Monaco;
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }
    }

    .thought-detail {
      display: flex;
      padding: var(--spacing-base) 12px;
      // justify-content: center;
      // align-items: center;
      gap: 10px;
      // align-self: stretch;

      margin-top: 5px;
      border-radius: var(--radius-normal);
      background: #f7f8fa;
      // background: color(display-p3 0.9686 0.9725 0.9804);

      color: var(--color-text-secondary);

      /* caption/--caption-regular */
      // font-family: var(--font-family-normal);
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: 16px;

      /* 133.333% */
      /deep/ p {
        word-break: break-all;
        word-wrap: break-word;
        // background: pink;
        margin: 0;
      }
    }
    .thought-tips {
      // background-color: pink;
      display: flex;
      padding: var(--spacing-base-loose) 10px 4px 10px;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 10px;
      align-self: stretch;
      &-workflow {
        // background-color: purple;
        display: flex;
        padding: 3px 12px;
        align-items: flex-start;
        gap: 10px;

        border-radius: 20px;
        background: #f3f5fb;
        // background: color(display-p3 0.9529 0.9608 0.9804);

        color: var(
          --gray---color-gray-5,
          var(--global-color-gray---color-gray-5, #b2b8c6)
        );
        // color: var(--gray---color-gray-5, var(--global-color-gray---color-gray-5, color(display-p3 0.7059 0.7216 0.7686)));
        // font-family: "PingFang SC";
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }
    }
  }
}
</style>
